package com.minaClient.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.minaClient.utils.Comunication;
import com.minaClient.utils.Consant;
import com.minaClient.utils.Msg;
import com.minaClient.utils.PropertiesUtil;

/**
 * Description:
 */
public class MinaService {
    boolean isConnection;
    ConnectionManager mManager;
    ConnectionConfig config;
    public static volatile boolean exitHeartBit ; 
    Logger log =Logger.getLogger(MinaService.class.getName());
    public static MinaService mMinaService=null;
    int i=0;
    int pierd=3;//断线重连时间
    public MinaService() {
    	mMinaService=this;
	}
    /**
     * 创建连接配置
     */
    private int readBufferSize=10240;
    private long connectionTimeout=10000;
    
    
    private Comunication com=new Comunication();
    private List<Object> list=new ArrayList<>();
    private Msg msg=new Msg();
    public  void minaClientStart(){
    	 config = new ConnectionConfig.Builder()
                 .setIp(PropertiesUtil.CLIENT_SEND_HOST)
                 .setPort(PropertiesUtil.CLIENT_MAIN_PORT)
                 .setReadBufferSize(readBufferSize)
                 .setConnectionTimeout(connectionTimeout).builder();
        mManager = new ConnectionManager(config);
        exitHeartBit=true;
        startConnection();
    }

     /**
      * 开始尝试连接
      * **/
    private void startConnection(){
    	  new Thread(new ConnectionThread()).start();
    }
    /**
     * 开始发送心跳数据
     */
    private void startHeartBit(){
    	 new Thread(new HeartBitThread()).start();
    	 log.debug( "启动心跳");
   }
    

	class ConnectionThread implements  Runnable {
		public void run() {
            while(true){
            	
                isConnection = mManager.connnect();
                if(isConnection){
                	i=0;
                	log.debug( "连接成功,并开始发送心跳数据");
                    startHeartBit();
                    break;
                }else {
                	i++;
                	pierd=i<10?5:10;
                }
                try {
                	log.debug( "尝试重新连接");
                    Thread.sleep(1000*pierd);
                    
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    log.debug( "尝试重新连接"+e.getMessage());
                    disConnect();
                }
         }
		}
    }
	/**
	 * 关闭连接
	 */
	 public void disConnect(){
         mManager.disContect();
         log.debug( "关闭连接：");
     }	
	 /**
	  * 创建心跳线程
	  * @author Administrator
	  *
	  */
	 class HeartBitThread implements  Runnable {
		 
			public void run() {
				log.debug( exitHeartBit);
	            while(exitHeartBit&&isConnection){
	                try {
	                	log.debug("发送心跳数据"+exitHeartBit);
	                	
	                	list.clear();
//	                	发送心跳命令
	                	//SessionManager.getInstance().writeToServer(JSON.toJSON(ResourcesJob.resources()));
	                	msg.setCode(Consant.CODE_BITHEART);
	                	msg.setMsg(Consant.MSG_BITHEART);
	                	list.add(ResourcesJob.resources());
	                	
	                	com.setList(list);
	                    com.setMsg(msg);
	                    
	                    //发送心跳数据
	                	SessionManager.getInstance().writeToServer(JSON.toJSON(com));
	                    Thread.sleep(10000);
	                } catch (InterruptedException e) {
	                	e.printStackTrace();
	                    log.debug( "HeartBitThread InterruptedException"+e.getMessage());
	                    disConnect();
	                }
	             }
	            //关闭线程
	            try {
					Thread.currentThread().join();
				} catch (InterruptedException e) {
					log.debug( "HeartBitThread InterruptedException Thread.currentThread().join()");
				}
			}
			
	    }
	 
	 /**
	  * 尝试重新连接和发送心跳数据
	  */
	 public void reStartConBit(){
		 startConnection();
	 }
	 
}
